import { Component } from '@angular/core';
import {IonicPage, NavController, NavParams, ToastController} from 'ionic-angular';
import { LocalStorProvider } from '../../providers/local-stor/local-stor';
import {ApiProvider} from "../../providers/api/api";
import {UpdatePasswordPage} from "../update-password/update-password";
import { AppVersion } from '@ionic-native/app-version';
import { AlertController } from 'ionic-angular';
import {MyScoreListPage} from "../my-score-list/my-score-list";
import {LoginPage} from "../login/login";
import {SourceViewProvider} from "../../providers/source-view/source-view";
import {ImgUploadProvider} from "../../providers/img-upload/img-upload";
import {AndroidPermissions} from "@ionic-native/android-permissions";
import {ImagePicker} from "@ionic-native/image-picker";
import {MySignListPage} from "../my-sign-list/my-sign-list";
import {FaceProvider} from "../../providers/face/face";

/**
 * Generated class for the PersonalCentrePage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-personal-centre',
  templateUrl: 'personal-centre.html',
})
export class PersonalCentrePage {
  user_id;
  user_image;
  stu_no;
  email;

  macAddr;

  real_name;

  courseNum;

  oldUserImage;
  showCode=0;

  // 是否存在继续授课时的padding;
  padding = 0;
  constructor(public navCtrl: NavController, public navParams: NavParams, private storage: LocalStorProvider, public http: ApiProvider, private appVersion: AppVersion,
              private alertCtrl: AlertController, public souceview: SourceViewProvider, private imgUpload:ImgUploadProvider,
              private androidPermissions: AndroidPermissions, public face: FaceProvider, public toastCtrl: ToastController)
  {
  }

  async faceSign(){
    let imgBase;
    try{
      imgBase = await this.face.signCamera();
    }
    catch (e) {

    }
    let user_id = await this.storage.getKey('user_id');

    const checked = await this.http.checkFace({user_id: this.user_id});

    let toast;

    if(checked['Code'] === '11111111'){
      toast = this.toastCtrl.create({
        message: checked['Message'],
        duration: 3000,
        position: 'bottom'
      });
    } else {
      this.http.faceSign({image: imgBase, user_id: user_id}).subscribe(res => {

        toast = this.toastCtrl.create({
          message: res['Message'],
          duration: 3000,
          position: 'bottom'
        });

        toast.present();
      })
    }
  }

  ionViewDidLoad() {
    this.courseNum=+this.navParams.get("courseNum");
    this.storage.getKey("user_id").then(val => {
      this.user_id = val;
    });

    this.storage.getKey("email").then(val => {
      this.email = val;
    });

    this.storage.getKey("studentid").then(val => {
      this.stu_no = val;
    });

    this.storage.getKey("headpicture").then(val => {
      this.user_image = this.http.filePath + val;
      this.oldUserImage=val;
    });

    this.storage.getKey("macAddr").then(val => {
      this.macAddr = val;
    });

    this.storage.getKey("real_name").then(val => {
      this.real_name = val;
    });

    const hasPermission = this.androidPermissions.checkPermission(
      this.androidPermissions.PERMISSION.CAMERA
    );

    if (!hasPermission) {
      const result = this.androidPermissions.requestPermission(
        this.androidPermissions.PERMISSION.CAMERA
      );

      if (!result['hasPermission']) {
        throw new Error('Permissions required');
      }

      return;
    }
  }

  /**
   * 修改密码
   */
  updatePassword() {
    this.navCtrl.push(UpdatePasswordPage);
  }

  /**
   * 获取版本号
   */
  checkVersion() {
    this.http.checkVersion("personalCentre");
  }

  /**
   * 查看我的成绩
   */
  queryScoreList() {
    if(this.courseNum==0)
    {
      this.http.showToast("你还没有加入任何课程，请先申请加入课程","bottom");
    }
    else
    {
      this.navCtrl.push(MyScoreListPage, {student_id: this.user_id});
    }
/*    this.http.post("/index/bannerIndex.do",{studentId:+this.user_id,bannerType:1}).subscribe(item=>{
      if(item["Code"]!="11111111")
      {
        if(item["indexCourseList"].length==0)
        {
          this.http.showToast("你还没有加入任何课程，请先申请加入课程","bottom");
        }
      }
      else
      {
        this.navCtrl.push(MyScoreListPage, {student_id: this.user_id})
      }
    })*/
  }

  /**
   * 退出登录
   */
  logout() {
    let confirm = this.alertCtrl.create({
      title: '温馨提示',
      message: '退出当前账号后您将不能使用本应用，真的要退出吗？',
      buttons: [
        {
          text: '取消',
          handler: () => {
          }
        },
        {
          text: '退出',
          handler: () => {
            this.storage.remove("user_id");
            this.storage.remove("email");
            this.storage.remove("studentid");
            this.storage.remove("headpicture");

            this.navCtrl.setRoot(LoginPage);
            //this.writeAccessLog();
          }
        }
      ]
    });
    confirm.present();
  }

/*  /!**
   * 登出回写访问记录
   *!/
  writeAccessLog() {
    this.http.post("/userstu/logout.do", {userId: this.user_id, macAddr: '70:81:eb:99:79:15'}).subscribe(item => {
      if (item["Code"] == "11111111") {
        this.http.showToast(item["Message"], "bottom");
      }
      else {
        this.storage.remove("user_id");
        this.storage.remove("email");
        this.storage.remove("studentid");
        this.storage.remove("headpicture");
        this.storage.remove("macAddr");

        this.navCtrl.setRoot(LoginPage);
        /!*this.navCtrl.push(LoginPage);*!/
      }
    })
  }*/

  /**
   * 关于范课堂
   */
  aboutApk() {
    this.souceview.showPage(this.http.mobileUrl + "/html/aboutfourinOne.html", "关于泛课堂");
  }

  /**
   * 使用说明
   */
  useOf() {
    this.souceview.download(this.http.mobileUrl + "/html/userOf.pdf", "/html/userOf.pdf", 0);
  }

  /**
   * 上传头像
   */
  uploadFile()
  {
    this.initImgSer();
    this.imgUpload.showPicActionSheet();
  }

  /**
   * 头像上传相关设置
   */
  initImgSer() {
    this.imgUpload.uploadApi = '/userstu/updateHeadPic.do';
    this.imgUpload.oldUserImage=this.oldUserImage;
    this.imgUpload.user_id=this.user_id;//133
    this.imgUpload.Type="Head";
    this.imgUpload.maxUploadCount=1;

    this.imgUpload.upload.success= (data)=> {
      if(data["Code"]=="00000000")
      {
        //this.imgUpload.loading.dismiss();

        this.user_image=this.http.filePath+data["ImgUrl"];
        this.storage.setKey("headpicture",data["ImgUrl"]);
        this.oldUserImage=data["ImgUrl"];

      }
      else
      {
        //this.imgUpload.loading.dismiss();
        this.http.showToast(data["Message"],'bottom');
      }
    };

    this.imgUpload.upload.error= (err)=> {
      this.http.showToast('上传失败','bottom');
    };
  }

  /**
   * 分享朋友
   */
  shareFriends()
  {
    this.showCode=1;
  }

  mySignList()
  {
    this.navCtrl.push(MySignListPage,{userId:this.user_id});
  }
}
